<template>
  <el-row style="padding: 5px">
    <el-col :span="8">
      <h4>
        <strong>&nbsp;&nbsp;&nbsp;{{ tableInfo.dataModel.dataName }}</strong>
        /
        <small>{{ tableInfo.dataModel.dataSqlName }}</small>
      </h4>
    </el-col>
    <el-col :span="8" style="text-align: right">
      <el-button type="success" v-if="tableInfo.dataModel.canInsert" @click="opTableData(1)">
        新增
      </el-button>
      <el-button type="success" v-if="tableInfo.dataModel.canUpdate" @click="opTableData(2)">
        修改
      </el-button>
      <el-button type="success" v-if="tableInfo.dataModel.canDelete" @click="opTableData(3)">
        删除
      </el-button>
      <el-button
        type="success"
        v-for="click in tableInfo.dataModel.colClickList"
        @click="tableInfo.onColclick(click.value)"
        :key="click.name"
      >
        {{ click.name }}
      </el-button>
    </el-col>
    <el-col :span="8" style="text-align: right">
      <el-button type="success" @click="queryTable">查询</el-button>
      <el-button type="success" @click="tableInfo.addSearchConditon">增加查询条件</el-button>
      <el-button type="success" @click="tableInfo.clearSearchConditon">清空查询条件</el-button>
    </el-col>
  </el-row>
  <el-row>
    <el-col
      :span="5"
      :offset="1"
      v-for="searchConditon in tableInfo.searchConditons"
      :key="searchConditon.queryName"
    >
      <el-input
        style="margin-top: 5px"
        v-model="searchConditon.value"
        placeholder="日期如:20170101"
      >
        <template #prepend>
          <el-select v-model="searchConditon.name" placeholder="请选择">
            <el-option
              v-for="item in tableInfo.queryConditions"
              :key="item.queryName"
              :value="item.queryName"
              :label="item.queryDescribe"
            />
          </el-select>
        </template>
      </el-input>
    </el-col>
  </el-row>
  <el-row>
    <el-table
      ref="dynamicTable"
      row-key="id"
      v-loading="loading"
      :data="dataSource"
      :stripe="true"
      :highlight-current-row="true"
      @selection-change="handleCurrentChange"
      style="width: 100%; margin-top: 5px"
    >
      <el-table-column type="selection" />
      <el-table-column
        v-for="(col, index) in tableInfo.colModel"
        :key="index"
        :label="col.colName"
        :prop="col.colSqlName"
        :width="col.width ? col.width : 'auto'"
        :show-overflow-tooltip="true"
      >
        <template #default="scope">
          <div v-if="col.colDataType == 'bol'">{{ scope.row[col.colSqlName] ? '是' : '否' }}</div>
          <div v-else-if="col.colDataType == 'upload'">
            <!-- <UploadInfo :uploadStr="record[col.colSqlName]" /> -->
          </div>
          <div v-else-if="col.colDataType == 'enum'">{{ getEnumName(scope.row, col) }}</div>
          <div v-else>
            {{ scope.row[col.colSqlName] }}
          </div>
        </template>
      </el-table-column>
    </el-table>
  </el-row>
  <el-row>
    <el-col :offset="8">
      <el-pagination
        layout="total, sizes, prev, pager, next, jumper"
        :page-size="pagination.pageSize"
        :current-page="pagination.current"
        :total="pagination.total"
        @size-change="(v) => handleTableChange(undefined, v)"
        @current-change="(v) => handleTableChange(v, undefined)"
      />
    </el-col>
  </el-row>
  <el-dialog
    :title="(opType == 1 ? '新增' : opType == 2 ? '更新' : '删除') + tableInfo.dataModel.dataName"
    :footer="null"
    v-model="showModal"
    style="margin-bottom: 10px"
  >
    <DynamicForm
      :dataSchema="tableInfo"
      :dataInstance="tableInfo.modelInstance"
      :opType="opType"
      @sumbit="sumbit"
      @cancel="cancel"
    />
  </el-dialog>
</template>
<script setup lang="ts">
import { DynamicForm } from '@/components/DynamicForm'
import { deepClone } from '@/utils'
import {
  ElMessage,
  ElRow,
  ElCol,
  ElInput,
  ElSelect,
  ElOption,
  ElTable,
  ElTableColumn,
  ElPagination,
  ElDialog
} from 'element-plus'
import { computed, onMounted, reactive, ref } from 'vue'
import request from '@/config/axios'
const table = ref('')
const dynamicTable = ref()
const loading = ref(false)
const dataSource = ref([])
const opType = ref(0) //0 无操作,1 新增,2 更新,3 删除
const showModal = computed({
  get: () => !(opType.value == 0),
  set: (val) => {
    if (!val) {
      opType.value = 0
    }
  }
})
const pagination = reactive({
  total: 10,
  current: 1,
  pageSize: 10,
  showQuickJumper: true,
  showSizeChanger: true
})
const tableInfo: any = reactive({
  dataModel: {},
  queryConditions: [],
  searchConditons: [{ name: '', value: '' }],
  colModel: [{ colDataType: '', colSqlName: '' }],
  selectModel: { id: null },
  modelInstance: { id: null },
  addSearchConditon: () => {
    if (tableInfo.searchConditons.length == 6) {
      ElMessage.warning('请不要添加过多查询条件')
      return
    }
    tableInfo.searchConditons.push({ name: '', value: '' })
  },
  clearSearchConditon: () => {
    tableInfo.searchConditons = [{ name: '', value: '' }]
  },
  onColclick: (url) => {
    if (!tableInfo.selectModel.id) {
      ElMessage.warning('请先选择需要操作的行')
    } else {
      tableInfo.modelInstance = deepClone(tableInfo.selectModel)
      request.postFull(
        {
          url: url,
          data: tableInfo.modelInstance
        },
        loading
      )
    }
  }
})
function handleCurrentChange(selection) {
  if (selection.length > 1) {
    //当选中两个以上的选项时
    dynamicTable.value.clearSelection() //清空所有
    //再把第一次选中的勾选上
    dynamicTable.value.toggleRowSelection(selection[selection.length - 1])
    //selectObj 用来保存勾选的那一项内容
    tableInfo.selectModel = selection[selection.length - 1]
  } else if (selection.length == 1) {
    tableInfo.selectModel = selection[0]
  } else {
    tableInfo.selectModel = { id: null }
  }
}
function sumbit(dataInstance, formSpinning) {
  formSpinning.value = true
  let url = ''
  if (opType.value === 2) {
    url = '/infra/base/dynamicTable/editTableData'
  } else if (opType.value === 1) {
    url = '/infra/base/dynamicTable/addTableData'
  } else if (opType.value === 3) {
    url = '/infra/base/dynamicTable/deleteTableData'
  }
  request
    .postFormFull({
      url: url,
      data: {
        id: dataInstance.id,
        newModelData: JSON.stringify(dataInstance),
        dataSqlName: table.value
      }
    })
    .then(() => {
      opType.value = 0
      tableInfo.selectModel = dataInstance
      loadData(pagination.current, pagination.pageSize)
    })
    .finally(() => {
      formSpinning.value = false
    })
}
function cancel() {
  opType.value = 0
}
function opTableData(t) {
  if ((t == 2 || t == 3) && !tableInfo.selectModel.id) {
    ElMessage.warning('请先选择需要更新或删除的数据列')
    return
  }
  if (t == 2 || t == 3) {
    tableInfo.modelInstance = deepClone(tableInfo.selectModel)
  }
  if (t == 1) {
    tableInfo.modelInstance = { id: null }
  }
  opType.value = t
}
function handleTableChange(current, pageSize) {
  loadData(current, pageSize)
}
function getEnumName(reacord, col) {
  let name = ''
  col.colEnumList.forEach((element) => {
    if (element.value === reacord[col.colSqlName] + '') {
      name = element.name
    }
  })
  return name
}
function queryTable() {
  loadData(pagination.current, pagination.pageSize)
}
function loadData(pn = 1, ps = 10) {
  loading.value = true
  tableInfo.modelInstance.id = null
  request
    .postFormFull({
      url: '/infra/base/dynamicTable/listTableData',
      data: {
        table: table.value,
        queryData: JSON.stringify(tableInfo.searchConditons),
        pageSize: ps,
        pageNum: pn
      }
    })
    .then((data) => {
      dataSource.value = data.list
      loading.value = false
      pagination.current = pn
      pagination.pageSize = ps
      pagination.total = data.total
    })
    .finally(() => {
      loading.value = false
    })
}
function initTable() {
  loading.value = true
  let url = window.location.hash
  table.value = url.substring(url.lastIndexOf('/') + 1)
  request
    .get({
      url: '/infra/base/dynamicTable/getTable/' + table.value
    })
    .then((data) => {
      tableInfo.dataModel = data.dataModel
      tableInfo.queryConditions = data.queryConditions
      tableInfo.colModel = data.colModel
      loadData()
    })
}
onMounted(() => {
  initTable()
})
</script>
<style>
.el-table-column--selection.is-leaf.el-table__cell .cell {
  display: none;
}
</style>
